//
//  ImageHelper.m
//  YinHang
//
//  Created by 张亚哲 on 14/10/29.
//  Copyright (c) 2014年 孙彦鹏. All rights reserved.
//

#import "ImageHelper.h"

@implementation ImageHelper{
    NSURLConnection *connection_;
    NSMutableData *responseData_;
    UIImage *img;
    UIActivityIndicatorView *activity;
}

-(void)dealloc{
    [connection_ cancel];
    img = nil;
    connection_ = nil;
    responseData_ = nil;
    activity = nil;
    
}
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

-(void)imgWithUrl:(NSString *)urlstr{
    // UIImage *backImg = []
    activity = [[UIActivityIndicatorView alloc]init];
    activity.center = self.center;
    [self addSubview:activity];
    [activity startAnimating];
    NSURL *url = [NSURL URLWithString:urlstr];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    connection_ = [NSURLConnection connectionWithRequest:request delegate:self];
    
}

#pragma mark - NSURLConnectionDataDelegate Delegate Method

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    
    NSLog(@"didFailWithError:%@", error);
    connection_ = nil;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    
    NSLog(@"didReceiveResponse");
    responseData_ = [NSMutableData data];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    
    NSLog(@"didReceiveData");
    [responseData_ appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    
    NSLog(@"connectionDidFinishLoading");
    img = [UIImage imageWithData:responseData_];
    self.image = img;
    [activity stopAnimating];
    connection_ = nil;
    activity = nil;
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse {
    [activity stopAnimating];
    NSLog(@"[已缓存数据]willCacheResponse\ncache_response:%@\ncache_data:%@", cachedResponse.response, cachedResponse.data);
    return cachedResponse;
}


@end
